package com.atguigu.stack_03;

import java.util.Scanner;

public class ArrayStackDemo {

	public static void main(String[] args) {
		//???????ArrayStack ??????
		//????????ArrayStack????->????
		ArrayStack stack = new ArrayStack(4);
		String key = "";
		boolean loop = true; //?????????????
		Scanner scanner = new Scanner(System.in);
		
		while(loop) {
			System.out.println("show: ???????");
			System.out.println("exit: ???????");
			System.out.println("push: ????????????(???)");
			System.out.println("pop: ?????????????(???)");
			System.out.println("????????????");
			key = scanner.next();
			switch (key) {
			case "show":
				stack.list();
				break;
			case "push":
				System.out.println("???????????");
				int value = scanner.nextInt();
				stack.push(value);
				break;
			case "pop":
				try {
					int res = stack.pop();
					System.out.printf("??????????? %d\n", res);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				break;
			case "exit":
				scanner.close();
				loop = false;
				break;
			default:
				break;
			}
		}
		
		System.out.println("???????~~~");
	}

}

//??????? ArrayStack ????
class ArrayStack {
	private int maxSize; // ????С
	private int[] stack; // ???飬???????????????????????
	private int top = -1;// top??????????????-1
	
	//??????
	public ArrayStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[this.maxSize];
	}
	
	//???
	public boolean isFull() {
		return top == maxSize - 1;
	}
	//???
	public boolean isEmpty() {
		return top == -1;
	}
	//???-push
	public void push(int value) {
		//???ж???????
		if(isFull()) {
			System.out.println("???");
			return;
		}
		top++;
		stack[top] = value;
	}
	//???-pop, ??????????????
	public int pop() {
		//???ж??????
		if(isEmpty()) {
			//?????
			throw new RuntimeException("???????????~");
		}
		int value = stack[top];
		top--;
		return value;
	}
	//?????????[?????]?? ?????????????????????????
	public void list() {
		if(isEmpty()) {
			System.out.println("???????????~~");
			return;
		}
		//??????????????????
		for(int i = top; i >= 0 ; i--) {
			System.out.printf("stack[%d]=%d\n", i, stack[i]);
		}
	}
	
}
